package org.wzq.utils.socket;

import org.wzq.config.AppUrl;
import org.wzq.utils.ConvertUtils;
import org.wzq.utils.Logger;

import java.io.IOException;

/**
 * project:
 * author: wzq
 * date: 2014/8/9
 * description:
 */
public class SocketManager {
    private SocketConnect socket;
    private Logger logger = Logger.newLogger(true, SocketManager.class);

    private static SocketManager manager = new SocketManager();

    public static SocketManager getInstance() {
        return manager;
    }

    private SocketManager() {
    }

    // if not set, use default
    private SocketMsgHandler msgHandler;
    private SocketMsgHandler defMsgHandler = new SocketMsgHandler() {
        @Override
        public void onReceiveMsg(byte[] msg) {
            logger.v("handle msg");
            ConvertUtils.printByteArray(msg);
        }
    };

    public void setSocketMsgHandler(SocketMsgHandler msgHandler) {
        this.msgHandler = msgHandler;
    }

    public boolean isAvailable() {
        return socket != null && socket.isAvailiable();
    }

    public boolean sendMsg(byte[] msg) {
        return socket.sendMsg(msg);
    }

    public boolean sendMsg(String msg) {
        byte[] bytes = null;
        try {
            bytes = ConvertUtils.string2Bytes(msg, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return socket.sendMsg(bytes);
    }

    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                startInternal();
            }
        }).start();
    }

    private void startInternal() {
        socket = new SocketConnect(AppUrl.getSocketIp(), AppUrl.SOCKET_PORT);
        socket.setSocketMsgHandler(msgHandler == null ? defMsgHandler : msgHandler);
        socket.connect();
    }

    public void stop() {
        if (socket != null) {
            socket.disConnect();
            socket = null;
        }
    }
}
